import { getById, saveDictType } from '@/api/sys/dict'
import { computed, defineComponent, PropType, reactive, ref, watch } from 'vue'

export interface IDictForm {
  id?: string;
  name?: string;
  typeValue?: string;
  dictTypeOrder?: number;
}

export default defineComponent({
  name: 'DictTypeForm',
  props: {
    visible: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    formId: {
      type: String as PropType<string>,
      default: ''
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      form: {} as IDictForm
    })
    const ruleForm = ref<any>(null)
    const formRules = {
      name: [
        { required: true, message: 'required', trigger: 'blur' }
      ]
    }

    const closeDialog = () => emit('update:visible', false)

    const handleOk = () => {
      ruleForm.value.validate().then(() => {
        saveDictType(state.form).then((res) => {
          if (res.state) {
            closeDialog()
          }
        })
      })
    }

    watch(computed(() => props.formId), (formId) => {
      if (formId) {
        getById(formId).then((res) => {
          state.form = res.result.form
          console.log(state.form)
        })
      } else {
        state.form = {}
      }
    })

    return () => {
      return (
        <a-modal
          visible={props.visible}
          title="Modal"
          ok-text="确认"
          cancel-text="取消"
          onCancel={closeDialog}
          onOk={handleOk}
        >
          <a-form
            rules={formRules}
            ref={ruleForm}
            model={state.form}
          >
            <a-form-item has-feedback label="标志" name="name">
              <a-input v-model={[state.form.name, 'value']} autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="key值" name="typeValue">
              <a-input v-model={[state.form.typeValue, 'value']} autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="排序" name="dictTypeOrder">
              <a-input-number v-model={[state.form.dictTypeOrder, 'value']} />
            </a-form-item>
          </a-form>
        </a-modal>
      )
    }
  }
})
